package cn.cheneyjoo.controller;

import cn.cheneyjoo.DTO.ResponseDTO;
import cn.cheneyjoo.Model.OrderDetail;
import cn.cheneyjoo.Model.OrderMain;
import cn.cheneyjoo.feigninterface.GoodsFeignInterface;
import cn.cheneyjoo.service.OrderService;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/order")
@RefreshScope
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private GoodsFeignInterface goodsFeignInterface;

    //获取配置中心的信息
    @Value("${slogan}")
    private String slogan;

    @PostMapping
    public ResponseDTO saveOrder(OrderMain orderMain) {
        boolean b = orderService.saveOrder(orderMain);
        ResponseDTO responseDTO = new ResponseDTO(b ? 200 : 203, b ? "成功" : "失败", null);
        return responseDTO;
    }

    /**
     * 分页查询
     *
     * @param pageIndex 页码
     * @param pageSize  每页条数
     * 订单创建时间范围、订单状态（未支付、已支付、已失效、已删除）
     * @return
     */
    @GetMapping("/page/{pageIndex}")
    public ResponseDTO getOrdersByPage(@PathVariable int pageIndex, int pageSize, String StartTime, String EndTime, String OrderStatus)  {
        Map<String, String> where = new HashMap<>();
        if (Optional.ofNullable(StartTime).isPresent()) {
            where.put("StartTime", StartTime);
        }
        if (Optional.ofNullable(EndTime).isPresent()) {
            where.put("EndTime", EndTime);
        }
        if (Optional.ofNullable(OrderStatus).isPresent()) {
            where.put("OrderStatus", OrderStatus);
        }
        List<OrderMain> orderMains = orderService.getOrdersByPage(pageIndex, pageSize, where);
        return new ResponseDTO<>(200, "成功", orderMains);
    }

    /**
     * 根据订单ID查询订单明细表详情
     *
     * @param orderId
     * @return
     */
    @GetMapping("/orderdetail/{orderId}")
    public ResponseDTO getOrderDetailByOrderId(@PathVariable int orderId) {
        List<OrderDetail> orderDetailList = orderService.getOrderDetailByOrderId(orderId);
        for (OrderDetail orderDetail : orderDetailList) {
            orderDetail.setProduct(goodsFeignInterface.getOneProduct(orderDetail.getProductId()));
        }
        return new ResponseDTO<>(200, "成功", orderDetailList);
    }

    /**
     * 获取slogan
     * @return
     */
    @GetMapping("/slogan")
    public ResponseDTO getSlogan() {
        return new ResponseDTO(200, "成功", slogan);
    }
}
